import { createWebHistory, createRouter } from 'vue-router'
import { getToken } from '@/utils/auth'
import usePermissionStore from '@/store/permission'
// 公共路由
export const constantRoutes = [
  {
    path: '/login',
    component: () => import('@/views/login'),
    hidden: true
  },
  {
    path: '',
    component: () => import('@/layout/index'),
    redirect: '/index',
    children: [
      {
        path: '/index',
        component: () => import('@/views/index'),
        name: 'Index',
        meta: { title: '首页', icon: 'dashboard', affix: true }
      }
    ]
  },
  {
    path: "/:pathMatch(.*)*",
    component: () => import('@/views/error/404'),
    hidden: true
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes: constantRoutes
});

const whiteList = ["/login"]

const isWhiteList = (path) => {
  return whiteList.indexOf(path) !== -1
}

router.beforeEach((to, from, next) => {
  if (getToken()) {
    if (to.path === '/login') {
      next({ path: '/' })
    } else if (isWhiteList(to.path)) {
      next()
    } else {
      if (usePermissionStore().sidebarRouters.length === 0) {
        usePermissionStore().generateRoutes().then(accessRoutes => {
          // 根据roles权限生成可访问的路由表
          accessRoutes.forEach(route => {
            router.addRoute(route) // 动态添加可访问路由表
          })
          console.log("🚀 ~ usePermissionStore ~ router.getRoutes():", router.getRoutes())
          next({ ...to, replace: true }) // hack方法 确保addRoutes已完成
        })
      } else {
        next()
      }
    }
  } else {
    if (isWhiteList(to.path)) {
      next()
    } else {
      next('/login')
    }
  }
})
export default router